<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>音频可视化</title>
</head>
<body>
<audio id="myAudio" src="../闺蜜的话.m4a" ></audio>
<canvas id="myCanvas" ></canvas>
<button id="playButton">播放</button>
<!-- JavaScript 代码 -->
<script>
    // 获取 canvas 元素
    var canvas = document.getElementById("myCanvas");
    canvas.setAttribute("width",window.innerWidth+"")
    canvas.setAttribute("height",window.innerHeight+"")
    // 获取音频元素
    var audio = document.getElementById("myAudio");

    // 创建音频上下文
    var audioCtx = new window.AudioContext();

    // 创建音源节点
    var source = audioCtx.createMediaElementSource(audio);

    // 创建分析节点
    var analyser = audioCtx.createAnalyser();

    // 将分析节点连接到音源节点
    source.connect(analyser);

    // 将分析节点连接到音频上下文的目标节点
    analyser.connect(audioCtx.destination);

    // 设置音频的播放和暂停控制
    var playButton = document.getElementById("playButton");
    playButton.addEventListener("click", function() {
        if (audio.paused) {
            audio.play();
        } else {
            audio.pause();
        }
    });

    // 绘制音频可视化
    var canvasCtx = canvas.getContext("2d");
    var bufferLength = analyser.frequencyBinCount;
    var dataArray = new Uint8Array(bufferLength);

    function draw() {
        requestAnimationFrame(draw);
        analyser.getByteFrequencyData(dataArray);
        canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
        canvasCtx.fillStyle = "red";
        var barWidth = (canvas.width / bufferLength) * 2.5;
        var barHeight;
        var x = 0;
        for(var i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];
            canvasCtx.fillRect(x, canvas.height - barHeight / 2, barWidth, barHeight / 2);
            x += barWidth + 1;
        }
    }

    draw();
</script>
</body>
</html>
